<?php
namespace mobadmin\action;

use herosphp\bean\Beans;
use herosphp\core\Controller;
use herosphp\http\HttpRequest;
use herosphp\session\Session;
use herosphp\utils\AjaxResult;
use api\utils\WeiXinApi;
use herosphp\core\Log;

/**
 * login action
 * @package admin\action
 * @author yu
 */
class LoginAction extends Controller
{

    protected $serviceBean = 'mobadmin.manager.service';

    //登陆页面
    public function index(HttpRequest $request)
    {

        $service = Beans::get($this->serviceBean);
        if ($service->isLogin()) {
            location('/mobadmin/index/index');
        }

        $weixin_config = getConfig('weixin_config');

        //授权登录
        if (isset($_GET['url'])) {
            //urldecode,这里传过去的url，一定要urldecode
            $redirect_uri = getConfig('site_url') . '/mobadmin/login/signin?url=' .urldecode($_GET['url']);
            $weiXinApi = new WeiXinApi();
            $jump_url = $weiXinApi->get_authorize_url($weixin_config['appid'], $redirect_uri, 'STATE');
            Log::info("执行Login->index，判断有_GET['url'])，为{$_GET['url']}，开始授权微信登录{$jump_url},立即跳转");

            header("Location: $jump_url");
            //die;
        } else {
            $this->setView('sorry');
        }
    }


    public function signin(HttpRequest $request)
    {

        $service = Beans::get($this->serviceBean);
        $weixin_config = getConfig('weixin_config');

        //授权登录
        $code = '';

        if (isset($_GET['code'])) {
            $code = $_GET['code'];
        }

        //获取授权token,openid
        $WeiXinApi = new WeiXinApi();
        $result = $WeiXinApi->get_access_token($weixin_config['appid'], $weixin_config['appser'], $code);

        //echo "($appid, $appser , $code)\n";

        //print_r($result);

        //获取用户信息
        $wxUserInfo = $WeiXinApi->get_user_info($result['access_token'], $result['openid']);

        Log::info("进入signin, 稍后执行service->login");

        Log::info($wxUserInfo);

        $manager = $service->login($wxUserInfo);

        if ($manager) {
            Log::info("执行service->login，判断有user，立即跳转至{$_GET['url']}");


            if (isset($_GET['url'])) {
                $jump_url = getConfig('site_url') .$_GET['url'];
                header("Location: $jump_url");
            }
        } else {
            Log::info("执行service->login，判断无user");

            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '登陆失败，用户名或者密码错误');

        }

    }
    //退出登陆
    public function logout(HttpRequest $request)
    {
        $service = Beans::get($this->serviceBean);
        $service->logout();
        location("/mobadmin/login/index");
    }


    //退出登陆
    public function sss(HttpRequest $request)
    {
        $this->setView('login');
    }
}
